// 图片需要先以模块的方式导入
import logo from '@/assets/images/logo.png'
import './login.less'

import { Button, Form, Input, Toast } from 'antd-mobile'
import { useState } from 'react'
import { loginApi } from '@/http/api';
import { useNavigate } from 'react-router-dom';
import useToast from '@/hooks/toast';
// import { useDispatch } from 'react-redux'
// import { showToast } from '@/store/toastSlice'
export default function Login() {
    const navigate = useNavigate();
    // 定义两个数据 用户名和密码
    let [username, setUsername] = useState("12345678901");
    let [password, setPassword] = useState("wolfcode123");
    // 表单验证成功后并点击提交
    const login = () => {
        loginApi({
            username, password
        }).then(res => {
            if (res?.errCode == 0) {
                // 提示用户
                Toast.show({ icon: 'success', content: '登录成功' })
                // 存储token
                localStorage.setItem('token', res.data)
                // 跳转到首页
                navigate('/home')
            }
        })
    }
    const register = () => { }

    const toast = useToast()
    // const dispatch = useDispatch();
    const finish = () => {
        // isLoginPage ? login() : register()
        // 弹出层
        // dispatch(showToast({ text: '登录失败', type: 'success' }))
        toast('登录失败', 'err');
    }

    // 定义一个开关，表示当前是登录还是注册
    const [isLoginPage, setIsLoginPage] = useState(true);

    return <div className="login">
        <div className="logo">
            <img src={logo} alt="" />
        </div>
        {/* 这里使用 ant modile 的From 组件快速实现一个表单 */}
        <Form
            initialValues={{ username, password }}
            onFinish={finish}
            layout='horizontal'
            footer={
                <Button block type='submit' color='primary' size='large'>
                    {isLoginPage ? '登录' : '注册'}
                </Button>
            }
        >
            <Form.Header>{isLoginPage ? 'login' : 'register'} page</Form.Header>
            <Form.Item
                name='username'
                rules={[{ required: true, message: '姓名不能为空' }]}
            >
                <Input value={username} onChange={(value) => setUsername(value)} placeholder='请输入姓名' />
            </Form.Item>
            <Form.Item name='password' rules={[{ required: true, message: '密码不能为空' }]}>
                <Input
                    type="password"
                    placeholder='请输入密码'
                    value={password}
                    onChange={value => setPassword(value)}
                />
            </Form.Item>
        </Form>
        <div>
            <Button color='primary' fill='none' onClick={() => setIsLoginPage(!isLoginPage)}>
                去{isLoginPage ? '注册' : '登录'}
            </Button>
        </div>
    </div>
}